<?php
namespace backend\controllers;

use common\models\Tree;
use common\service\ConstantService;
use common\service\ExcelService;
use common\service\TreeService;
use common\service\LogaddService;
use yii\web\UploadedFile;

class TreeController extends BaseController
{
    /**
     * 分类列表页
     */
    public function actionIndex(){
        if($this->isGet() && $this->isAjax()){
            $trees = Tree::find()->asArray()->all();
            return $this->renderJson($trees,'',ConstantService::$response_success);

        }
        return $this->render('index');

    }

    /**
     * 添加分类
     */
    public function actionAddTree(){
        if($this->isAjax() && $this->isPost()){
            $data = $this->post();
            if(empty($data['tree_name']) || empty($data['icon'] )){
                return $this->renderJson([],'参数不合法',ConstantService::$response_fail);
            }
            $info = Tree::findOne(['tree_name'=>$data['tree_name']]);
            if(!empty($info['tree_name'])){
                return $this->renderJson([],'已经存在同名分来',ConstantService::$response_fail);
            }
            if($data['pid'] ){
                //有父级
                $parent_tree = Tree::findOne(['id'=>$data['pid']]);
                $data['level'] = $parent_tree['level'] +1;
                $data['parents'] = $parent_tree['parents'].','.$data['pid'];
            }else{
                $data['level'] = 1;
                $data['parents'] = '';
            }
            $tree_model = new Tree();
            $data['created_at'] = time();
            $tree_model->setAttributes($data);
            if($tree_model->save()){
                $str = $this->admin['username'].'在'.date("Y-m-d H:i:s").'新增分类'.$data['tree_name'];
                LogaddService::logAdd($this->admin['username'],$str);
                return $this->renderJson([],'添加成功',ConstantService::$response_success);
            }else{
                return $this->renderJson([],'添加失败',ConstantService::$response_fail);
            }
        }

        $trees = Tree::find()->asArray()->all();
        $trees = TreeService::getTreeCategory($trees);
        return $this->render('add-tree',['trees'=>$trees]);
    }

    /**
     * 修改分类
     */
    public function actionUpdateTree(){
        if($this->isPost() && $this->isAjax()){
            $data = $this->post();
            $row = Tree::findOne(['tree_name'=>$data['tree_name']]);
            if(!empty($row) && $row['id'] != $data['id']){
                return $this->renderJson([],'已经存在同名分类',ConstantService::$response_fail);
            }
            $childs = Tree::find()->where(['pid'=>$data['id']])->asArray()->all();
            $child_ids = array_column($childs,'id');
            if(in_array($data['pid'],$child_ids)){
                return $this->renderJson([],'不能修改到子类下面',ConstantService::$response_fail);
            }
            //获取层级

            if($data['pid']){
                $parent_tree = Tree::find()->where(['id'=>$data['pid']])->one();
                $data['level'] = $parent_tree['level']+1;
                $child_level = $data['level']+1;
            }else{
                $data['level'] = 1;
                $child_level = 2;
            }
            $current_tree = Tree::findOne(['id'=>$data['id']]);
            $current_tree->setAttributes($data);
            if($current_tree->save()){
                if(!empty($child_ids)){
                   Tree::updateAll(['pid'=>$data['id'],'level'=>$child_level],['id'=>$child_ids]);
//                    if(!$re){
//                        $this->renderJson([],'修改失败请稍后再试',ConstantService::$response_fail);
//                    }
                }
                $str = $this->admin['username'].'在'.date("Y-m-d H:i:s").'修改分类'.$data['tree_name'];
                LogaddService::logAdd($this->admin['username'],$str);
                $this->renderJson([],'修改成功',ConstantService::$response_success);
            }else{

                $this->renderJson([],'修改失败,请稍后再试',ConstantService::$response_fail);
            }
        }
        $id = $this->get('id');
        $info = Tree::find()->where(['id'=>$id])->asArray()->one();
        $trees = Tree::find()->asArray()->all();
        $trees = TreeService::getTreeCategory($trees);
        return $this->render('update-tree',['info'=>$info,'trees'=>$trees]);

    }

    /**
     * 删除分类
     */
    public function actionDeleteTree(){
        if($this->isAjax() && $this->isPost()){
            $id = $this->post('id');
            if(empty($id)){
                return $this->renderJson([],'参数不合法',ConstantService::$response_fail);
            }
            $tree  = Tree::findOne(['id'=>$id]);
            $tree_ids[] = $id;
            //二级
            $tree_2 = Tree::find()->where(['pid'=>$id])->asArray()->all();
            if(!empty($tree_2)){
                $tree_2_ids = array_column($tree_2,'id');
                array_push($tree_ids,$tree_2_ids);

                $tree_3 = Tree::find()->where(['pid'=>$tree_2_ids])->asArray()->all();
                if(!empty($tree_3)){
                    $tree_3_ids = array_column($tree_3,'id');
                    array_push($tree_ids,$tree_3_ids);
                }
            }
            $ids = '';
            foreach ($tree_ids as $key=>$item){

                if(is_array($item)){
                    $ids = $ids.','.implode($item,',');
                }else{
                    $ids = $ids.','.$item;
                }
            }
            unset($item);
            $tree_ids = explode(',',$ids);
            array_shift($tree_ids);

            $re = Tree::deleteAll(['id'=>$tree_ids]);
            if($re){
                $str = $this->admin['username'].'在'.date("Y-m-d H:i:s").'删除分类'.$tree['tree_name'];
                LogaddService::logAdd($this->admin['username'],$str);
                return $this->renderJson([],'删除成功',ConstantService::$response_success);
            }
            return $this->renderJson([],'删除失败',ConstantService::$response_fail);

        }
        return $this->renderJson([],'参数不合法',ConstantService::$response_fail);

    }
    /**
     * excle 批量导入分类
     */
    public function actionImportMenu(){
        if($this->isAjax() && $this->isPost()){
            // 获取上传的文件.
            $file = UploadedFile::getInstanceByName('excel');
            if(!in_array($file->getExtension(),['xls','xlsx']))
            {
                return $this->renderJson([],'未知的文件类型',ConstantService::$response_fail);
            }
            // 开始存文件.
            $file_path = \Yii::$app->getBasePath() .'/web/upload/'.time().'.'.$file->getExtension();
            // 开始移动文件
            $ret = move_uploaded_file($file->tempName,$file_path);
            if(!$ret)
            {
                return $this->renderJson([],'上传失败,请检查文件路径',ConstantService::$response_fail);
            }
            // 读取文件.返回读取的数据.
            $data = ExcelService::importExcel($file_path);
            if(!$data){
                return $this->renderJson([],'读取文件内容失败,请检查文件',ConstantService::$response_fail);
            }
            $res = $this->_batchaddtree($data);
            if($res['status'] !== true){
                return $this->renderJson([],$res['msg'],ConstantService::$response_fail);

            }
            return $this->renderJson([],$res['msg'],ConstantService::$response_success);
        }


    }

    /**
     * 批量添加分类
     * @param $data
     * @return array
     */
    private function _batchaddtree($data){
        unset($data[1]);
        if(empty($data)){
            return false;
        }
        $batch_data = [];
        $nobatch = '';
        foreach ($data as $val){
            $current_batch = [];
            $info = Tree::findOne(['tree_name'=>$val['A']]);
            if(!empty($info['tree_name'])){
                $nobatch .= '该分类'.$val['A'].'已存在';
                continue;
            }
            $current_batch['tree_name'] = $val['A'];
            $current_batch['pid'] = $val['B'];
            if($val['B'] ){
                //有父级
                $parent_tree = Tree::findOne(['id'=>$val['B']]);
                $current_batch['parents'] = $parent_tree['parents'].','.$current_batch['pid'];
                $current_batch['level'] = $parent_tree['level'] +1;
            }else{
                $current_batch['parents'] = '';
                $current_batch['level'] = 1;
            }
            $current_batch['created_at'] = time();
            $current_batch['updated_at'] = time();
            array_push($batch_data,$current_batch);
        }
        // ModelName::getDb()->createCommand()->batchInsert(表名,表的列名数组,要插入的二维数组数据)->execute();
        $ret = Tree::getDb()->createCommand()
            ->batchInsert('tree',[
                'tree_name', 'pid','parents','level','created_at','updated_at'
            ],$batch_data)->execute();
        if($ret){
            if(empty($nobatch)){
                $nobatch = '添加操作成功';
            }
            return ['status'=>true,'msg'=>$nobatch];
        }
        return ['status'=>false,'msg'=>'添加失败'];

    }




}